package com.dongdong.zhuangji.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Web安全配置类
 * 配置基本的认证和授权规则
 */
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级安全
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment env; // 注入Environment对象
    //配置用户信息服务
 /*   @Bean
    public UserDetailsService userDetailsService() {
       *//* //这里配置用户信息,这里暂时使用这种方式将用户存储在内存中
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;*//*

    }*/

    @Bean
    public PasswordEncoder passwordEncoder() {
        //密码为明文方式
        //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }
   @Bean
   public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
   }

  /*  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource())
                .and()
                .authorizeRequests()
                .antMatchers("/auth/**", "/pileData/**","/test/**").authenticated() // 保留原有认证要求
                .antMatchers("/controlPoints/page").permitAll() // 允许匿名访问分页接口
                .antMatchers("/controlPoints/**").authenticated() // 其他controlPoints接口仍需认证
                .anyRequest().permitAll() // 其它请求全部放行
                .and()
                .formLogin().disable(); // 关闭表单登录，使用OAuth2认证
                //.oauth2ResourceServer()
                //.jwt(); // 添加OAuth2资源服务器配置

        http.logout().logoutUrl("/auth/login-out"); // 退出地址

        // 根据环境变量决定是否启用HTTPS强制重定向
        if (Arrays.asList(env.getActiveProfiles()).contains("prod")) {
            http.requiresChannel()
                    .anyRequest().requiresSecure();
        }
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://192.168.1.245:5173");
        configuration.addAllowedOrigin("http://localhost:5173");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true); // 允许携带Cookie
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors() // 启用CORS配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**", "/login/**", "/api/public/**").permitAll() // 公开路径
                .anyRequest().authenticated() // 其他路径需要认证
                .and()
                .oauth2ResourceServer()
                .jwt(); // 使用JWT令牌验证
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        // 允许的前端域名
        configuration.setAllowedOriginPatterns(Arrays.asList(
                "http://localhost:5173",
                "http://192.168.1.245:5173",
                "http://hz14531ge93.vicp.fun",
                "http://haike.nat300.top",
                "http://dongdong.cloud/,",
                "http://www.dongdong.cloud/,",
                "http://wf8b8c26.natappfree.cc"
        ));

        // 允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList(
                "GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"
        ));

        // 允许的请求头
        configuration.setAllowedHeaders(Arrays.asList(
                "Authorization", "Content-Type", "X-Requested-With", "accept", "Origin",
                "Access-Control-Request-Method", "Access-Control-Request-Headers"
        ));

        // 暴露的响应头（确保前端可以访问这些头）
        configuration.setExposedHeaders(Arrays.asList(
                "Authorization", "Cache-Control", "Content-Language", "Content-Type",
                "Expires", "Last-Modified", "Pragma"
        ));

        // 允许携带凭证
        configuration.setAllowCredentials(true);

        // 预检请求缓存时间
        configuration.setMaxAge(3600L);

        // 注册CORS配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

}